#include "TcpServer.hpp"
#include "Protocol.hpp"

using namespace dsh_tcpserver;
using namespace dsh_protocol;

static void Usage(const std::string &process)
{
    std::cout << "\nUsage: " << process << " port\n"
              << std::endl;
}

void debug(int sock)
{
    std::cout << "test" << std::endl;
}

static Response calculatorHelp(const Request &req) // 拿到结构化的请求，返回结构化的相应
{
    Response resp(0, 0);
    switch (req.op_)
    {
    case '+':
        resp.result_ = req.x_ + req.y_;
        break;
    case '-':
        resp.result_ = req.x_ - req.y_;
        break;
    case '*':
        resp.result_ = req.x_ * req.y_;
        break;
    case '/':
        if (0 == req.y_) resp.code_ = 1;
        else resp.result_ = req.x_ / req.y_;
        break;
    case '%':
        if (0 == req.y_) resp.code_ = 2;
        else resp.result_ = req.x_ % req.y_;
        break;
    default:
        resp.code_ = 3;
        break;
    }
    return resp;
}

void calculator(int sock)
{
    while (true)
    {
        std::string str = Recv(sock); // 读到了一个请求
        Request req;
        req.Deserialize(str); // 反序列化
        Response resp = calculatorHelp(req); // 得到一个结构化的结果
        std::string respString = resp.Serialize(); // 结果序列化
        Send(sock, respString);
    }
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(1);
    }
    std::unique_ptr<TcpServer> server(new TcpServer(atoi(argv[1])));
    server->BindService(debug);
    server->Start();

    // Request req(123, 456, '+');
    // std::string s = req.Serialize();
    // std::cout << s << std::endl;

    // Request temp;
    // temp.Deserialize(s);
    // std::cout << temp.x_ << " " << temp.op_ << " " << temp.y_ << std::endl;

    return 0;
}